import "reflect-metadata";
import "dotenv/config";

import { serve } from "@hono/node-server";
import { Hono } from "hono";
import { prettyJSON } from "hono/pretty-json";
import AppDataSource from "./common/database";
import adminRoute from "./admin";
import { HTTPException } from "hono/http-exception";
import authRoute from "./admin/auth";
import { jwt } from "hono/jwt";
import { except } from "hono/combine";
import { timeout } from "hono/timeout";
import { logger } from "hono/logger";
import { cors } from "hono/cors";
import roleRoute from "./admin/role";
import permissionRoute from "./admin/permission";
import productRoute from "./admin/product";
import categoryRoute from "./admin/category";
import imageRoute from "./admin/image";
import storeRoute from "./admin/store";
import { serveStatic } from "@hono/node-server/serve-static";
import userRoute from "./admin/user";

const app = new Hono();

app.use(prettyJSON());

app.use(
  "*",
  cors({
    origin: "*",
    allowMethods: ["POST", "GET", "OPTIONS"],
    exposeHeaders: ["Content-Length", "X-Kuma-Revision"],
    maxAge: 600,
    credentials: true,
  })
);

AppDataSource.initialize()
  .then(() => {
    console.log("Data Source has been initialized!");
  })
  .catch((err) => {
    console.error("Error during Data Source initialization", err);
  });

// 静态资源
app.use("/*", serveStatic({ root: "./public" }));

console.log("process.env.NODE_ENV", process.env.NODE_ENV);

// 测试时不启用token验证
// if (process.env.NODE_ENV !== "development") {
//   app.use(
//     "/admin/*",
//     except(
//       ["/admin/auth/*", "/admin/image/*"],
//       jwt({ secret: process.env.SECRET })
//     )
//   );
// }

// 应用10秒超时
app.use("/api", timeout(10000));
app.use(logger());

app.route("/admin", adminRoute);
app.route("/admin/auth", authRoute);
app.route("/admin/role", roleRoute);
app.route("/admin/permission", permissionRoute);
app.route("/admin/product", productRoute);
app.route("/admin/category", categoryRoute);
app.route("/admin/image", imageRoute);
app.route("/admin/store", storeRoute);
app.route("/admin/user", userRoute);

app.onError((err, c) => {
  console.log(err);

  if (err instanceof HTTPException) {
    // 获取自定义响应
    return c.json({
      code: 400,
      message: err.message,
      env: process.env.NODE_ENV,
    });
  } else if (err.message) {
    return c.json({ code: 500, message: err.message });
  } else {
    return c.json({ code: 500, message: "system error" });
  }
});
console.log("process.env.PORT", process.env.PORT);
serve(
  {
    fetch: app.fetch,
    port: +process.env.PORT,
  },
  (info) => {
    console.log(`Server is running on http://localhost:${info.port}`);
  }
);
